<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
            //$this->layout = 'index';
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
                
                $thanh_vien = new ThanhVien();
                if(isset($_POST['ThanhVien']))
		{
			$thanh_vien->attributes=$_POST['ThanhVien'];
			// validate user input and redirect to the previous page if valid
			if($thanh_vien->save()) {
                            $this->redirect(Yii::app()->createUrl('site/index', array('reged' => '1')));
                        }
		}
                
		// display the login form
		$this->render('index',array(
                    'login'=>$model,
                    'thanh_vien' => $thanh_vien,
                ));
	}
        
        public function actionAjaxLike($id)
	{
            if(isset(Yii::app()->user->id)) {	
                $model = HinhLike::model()->findByAttributes(array('id_hinh'=>$id, 'id_thanh_vien'=>Yii::app()->user->id));
                if($model==null)
                {
                    $save = new HinhLike;
                    $save->id_hinh = $id;
                    $save->id_thanh_vien = Yii::app()->user->id;
                    $save->save();
                    echo "1";
                } else echo "0";
            } else 
                echo "0";
	}
        
        public function actionUploadStep2()
	{
		$idAlbum = Album::model()->layAlbumId();
                $model = Album::model()->findByPk($idAlbum);
                $imageModel = Hinh::model()->findAllByAttributes(array('id_album'=>$idAlbum));
                // renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
                if(isset($_POST['save_c']))
                {
                    foreach($imageModel as $row)
                    {
                        $model_image = Hinh::model()->findByPk($row["id"]);
                        $model_image->ten_hinh = $_POST['ten_hinh_'.$row["id"]];
                        if($_POST['mo_ta_hinh_'.$row["id"]]=='') $model_image->mo_ta = 'empty'; else 
                        $model_image->mo_ta = $_POST['mo_ta_hinh_'.$row["id"]];
                        $model_image->save();
                        if(isset($_POST['tag_'.$row["id"]])) {
                            $tag = $_POST['tag_'.$row["id"]];
                            foreach($tag as $row_tag)
                            {
                                $tag_model = Tag::model()->findByAttributes(array('ten_tag'=>$row_tag));
                                if($tag_model==null)
                                {
                                    $tag_new = new Tag();
                                    $tag_new->ten_tag = $row_tag;
                                    $tag_new->save();
                                    $HinhTag = new HinhTag();
                                    $HinhTag->id_hinh = $row["id"];
                                    $HinhTag->id_tag = $tag_new->id;
                                    $HinhTag->save();
                                } else {
                                    $HinhTag = new HinhTag();
                                    $HinhTag->id_hinh = $row["id"];
                                    $HinhTag->id_tag = $tag_model->id;
                                    $HinhTag->save();
                                }
                                
                            }
                        }
                    }
                    $this->redirect(array('viewalbum', 'id' => $idAlbum));
                }
		$this->render('uploadStep2', array(
                    'album' => $model,
                    'image' => $imageModel
                ));
	}
        
        public function actionEditAlbum($id)
	{
		$idAlbum = $id;
                $model = Album::model()->findByPk($idAlbum);
                $imageModel = Hinh::model()->findAllByAttributes(array('id_album'=>$idAlbum));
                // renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
                if(isset($_POST['save_c']))
                {
                    foreach($imageModel as $row)
                    {
                        $model_image = Hinh::model()->findByPk($row["id"]);
                        $model_image->ten_hinh = $_POST['ten_hinh_'.$row["id"]];
                        if($_POST['mo_ta_hinh_'.$row["id"]]=='') $model_image->mo_ta = 'empty';
                        $model_image->mo_ta = $_POST['mo_ta_hinh_'.$row["id"]];
                        $model_image->save();
                        
                        $checkQuyen = HinhTag::model()->findAllByAttributes(array('id_hinh' => $row["id"]));
                        if($checkQuyen != null){
                            foreach ($checkQuyen as $value) {
                                $temp = HinhTag::model()->findByPk($value['id']) ;
                                $temp->delete();
                            }
                        }
                        
                        if(isset($_POST['tag_'.$row["id"]])) {
                            $tag = $_POST['tag_'.$row["id"]];
                            foreach($tag as $row_tag)
                            {
                                $tag_model = Tag::model()->findByAttributes(array('ten_tag'=>$row_tag));
                                if($tag_model==null)
                                {
                                    $tag_new = new Tag();
                                    $tag_new->ten_tag = $row_tag;
                                    $tag_new->save();
                                    $HinhTag = new HinhTag();
                                    $HinhTag->id_hinh = $row["id"];
                                    $HinhTag->id_tag = $tag_new->id;
                                    $HinhTag->save();
                                } else {
                                    $HinhTag = new HinhTag();
                                    $HinhTag->id_hinh = $row["id"];
                                    $HinhTag->id_tag = $tag_model->id;
                                    $HinhTag->save();
                                }
                                
                            }
                        }
                    }
                    //$this->redirect(array('viewalbum', 'id' => $idAlbum));
                }
		$this->render('editAlbum', array(
                    'album' => $model,
                    'image' => $imageModel
                ));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('index',array(
                    'model'=>$model,
                ));
	}
        
        /**
	 * Ajax login
	 */
	public function actionAjaxLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
                        {
                            echo '<a class="login-link" href="' . Yii::app()->createUrl('site/logout') . '">Đăng xuất!</a>';
                            return;
                        }
		}
		// display the login form
		$this->renderPartial('login',array(
                    'model'=>$model,
                    'visible' => true,
                ));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
        
        public function actionExplore() {
            
            if(isset($_GET['key']))
            {
                $model = new Album();
            } else $model = new Album();
            $this->render('explore', array(
                'model' => $model,
            ));
        }
        
        public function actionMyAlbum() {
            
            $model = new Album();
            $this->render('myAlbum', array(
                'model' => $model,
            ));
        }
        
        public function actionDeleteImage($id) {            
            $model = Hinh::model()->findByPk($id);
            $check = 1;
            if(!isset(Yii::app()->user->id)) $check = 0;
            if(Yii::app()->user->id!=$model->idAlbum->id_thanh_vien) $check = 0;
            if($model!=null&&$check == 1) $model->delete();
            $this->redirect(array('editAlbum', 'id' => $model->idAlbum->id));            
        }

        
        public function actionViewAlbum() {
            if(isset($_GET['id'])) {
                $model = Album::model()->findByPk($_GET['id']);
                
                if($model) {
                    $hinh = new Hinh();
                    $binh_luan = new BinhLuanAlbum();
                    
                    $hinh->id_album = $model->id;
                    $binh_luan->id_album = $model->id;
                    
                    if(isset($_POST['BinhLuanAlbum'])) {
                        $binh_luan_moi = new BinhLuanAlbum();
                        $binh_luan_moi->attributes = $_POST['BinhLuanAlbum'];
                        $binh_luan_moi->id_album = $model->id;
                        $binh_luan_moi->thoi_diem_binh_luan = Date('y-m-d H-i-s');
                        $binh_luan_moi->id_thanh_vien = Yii::app()->user->id;
                        $binh_luan_moi->save();
                    }
                    
                    $this->render('album', array(
                        'model' => $model, 
                        'binh_luan' => $binh_luan,
                        'hinh' => $hinh,
                    ));
                }
            }
        }
        
        public function actionLightbox() {
            if(isset($_GET['id'])) {
                $model = Album::model()->findByPk($_GET['id']);
                
                if($model) {
                    $hinh = Hinh::model()->findAllByAttributes(array('id_album'=>$model->id));          
                    
                    
                    $this->renderPartial('lightbox', array(
                        'model' => $model,
                        'hinh' => $hinh,
                    ));
                }
            }
        }
        
        public function actionViewPhoto() {
            if(isset($_GET['id'])) {
                $hinh = Hinh::model()->findByPk($_GET['id']);
                
                if($hinh) {
                    $album = Album::model()->findByPk($hinh->id_album);
                    $binh_luan = new BinhLuanHinh();
                    
                    $binh_luan->id_hinh = $hinh->id;
                    
                    $count = count($album->hinhs);
                    $index = 0;
                    $prev_index = -1;
                    $next_index = 1;
                    $prev_id = null;
                    $next_id = null;
                    for($i = 0; $i < $count; ++$i) {
                        if($album->hinhs[$i]->id == $hinh->id) {
                            $index = $i;
                            $prev_index = $i - 1;
                            $next_index = $i + 1;
                            break;
                        }
                    }
                    
                    if($prev_index == -1) {
                        $prev_index = -1;
                    } else {
                        $prev_id = $album->hinhs[$prev_index]->id;
                    }
                    
                    if($next_index >= $count) {
                        $next_index = -1;
                    } else {
                        $next_id = $album->hinhs[$next_index]->id;
                    }
                    
                    if(isset($_POST['BinhLuanHinh'])) {
                        $binh_luan_moi = new BinhLuanHinh();
                        $binh_luan_moi->attributes = $_POST['BinhLuanHinh'];
                        $binh_luan_moi->id_hinh = $hinh->id;
                        $binh_luan_moi->thoi_diem_binh_luan = Date('y-m-d H-i-s');
                        $binh_luan_moi->id_thanh_vien = Yii::app()->user->id;
                        $binh_luan_moi->save();
                    }
                    
                    $this->render('photo', array(
                        'album' => $album, 
                        'binh_luan' => $binh_luan,
                        'hinh' => $hinh,
                        'prev_index' => $prev_index,
                        'next_index' => $next_index,
                        'index' => $index,
                        'next_id' => $next_id,
                        'prev_id' => $prev_id,
                        'count' => $count,
                    ));
                }
            }
        }
}
